package com.example.feidaolumanager.api

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.util.Log
import com.example.feidaolumanager.Constants
import com.example.feidaolumanager.LoginActivity
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Protocol
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

@SuppressLint("StaticFieldLeak")
object RetrofitClient {

    const val token: String = "tian123.a"

    lateinit var context: Context

    private var loggingInterceptor =
        HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)


    private val okHttpClient: OkHttpClient = OkHttpClient.Builder()
        .callTimeout(10, TimeUnit.SECONDS)
        .addInterceptor(loggingInterceptor)
        .addNetworkInterceptor(object : Interceptor {
            override fun intercept(chain: Interceptor.Chain): Response {
                val originalRequest = chain.request()
                //key的话以后台给的为准，我这边是叫token
                val updateRequest = originalRequest.newBuilder().header("token", token).build()
                Log.e(this@RetrofitClient.toString(), "intercept: 成功添加token:${token}")
                val response = chain.proceed(updateRequest)

                Log.e(this@RetrofitClient.toString(), "intercept: $response")
                if (response.code == 401) {
                    val intent = Intent(context, LoginActivity::class.java)
                    intent.addFlags(
                        Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent
                            .FLAG_ACTIVITY_NEW_TASK
                    )

                    val sharedPref: SharedPreferences = context.getSharedPreferences(
                        Constants.store_key, Context.MODE_PRIVATE
                    )
                    // 删除缓存
                    with(sharedPref.edit()) {
                        remove("user")
                        clear()
                        apply()
                    }
                    context.startActivity(intent)

                    return Response.Builder().protocol(Protocol.HTTP_1_1).message("")
                        .request(updateRequest)
                        .code(200)
                        .body("{}".toResponseBody())
                        .build()
                } else {
                    return response
                }
            }
        })
        .build()


    private val retrofit: Retrofit = Retrofit.Builder()
        .baseUrl(ApiService.BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .client(okHttpClient)
        .build()


    val apiService: ApiService = retrofit.create(ApiService::class.java)

    val loginService = retrofit.create(LoginService::class.java)

    val taskService = retrofit.create(TaskService::class.java)
    val machineService = retrofit.create(MachineService::class.java)

    val areasService = retrofit.create(AreasService::class.java)

    val fileUploadService = retrofit.create(FileUploadService::class.java)

    val agentService = retrofit.create(AgentService::class.java)
}